import { computed, ref } from 'vue';
import { defineStore } from 'pinia'
import {getShoppingCartList} from '@/common/request/api'
import type {CartGoodsItem,CartItem,CardFormData} from '@/common/request/api'
import {accAdd,accMul} from '@/common/utils'


export const useShoppingCart = defineStore('shoppingCart',() => {
	const cartGoodsList = ref<CartItem[]>([])
	const cartInvalidGoodsList = ref<CartGoodsItem[]>([])
	const cartProductAll = ref(0)
	const cartCheckMap = ref<Map<string,CartGoodsItem>>(new Map([]))
	const checkGoodsMoneyTotal = computed(() => {
		let num = 0
		cartGoodsList.value.map(bitem => {
			bitem.baskets.map(item => {
				const price = item.formJson ? (JSON.parse(item.formJson) as CardFormData).subFormDto.totalPrice :0
				if (cartCheckMap.value.has(item.id)) {
					num = accAdd(price,accAdd(num,accMul(item
						.productSku.price, item.basketCount)))
				}
			})
		})
		return num
	})
	
	const setCartGoodsList = (value:CartItem[]) => {
		cartGoodsList.value = value
	}
	
	const getCart = async () => {
		const res = await getShoppingCartList()
		setCartGoodsList(res.data||[])
		cartInvalidGoodsList.value = res.invalid||[]
		cartProductAll.value = res.productAll
		let _cartCheckMap = new Map<string,CartGoodsItem>([])
		res?.data.forEach(item => {
			item.baskets.forEach(goods => {
				if(cartCheckMap.value.has(goods.id)){
					_cartCheckMap.set(goods.id,goods)
				}
			})
		})
		setCartCheckMap(_cartCheckMap)
		
	}
	
	const setCartCheckMap = (value:Map<string,CartGoodsItem>) => {
		cartCheckMap.value = value
	}
	
	const removeCart = () => {
		cartGoodsList.value = []
		cartCheckMap.value = new Map([])
	}
	
	return {
		cartGoodsList,
		cartInvalidGoodsList,
		cartProductAll,
		cartCheckMap,
		setCartGoodsList,
		checkGoodsMoneyTotal,
		getCart,
		setCartCheckMap,
		removeCart
	}
})